﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using DotNet.Utilities;

namespace ConsoleApp
{
    public class Multithread
    {
        private const int ThreadNum = 5;
        private int _interval = 2000;
        private string _logFilePath = AppDomain.CurrentDomain.BaseDirectory + @"log_multi_thread.txt";
        private static object writeLock = new object();

        private ConcurrentQueue<Comment> CommentQueue=new ConcurrentQueue<Comment>();

        private Thread[] threads = null;
        public void Start()
        {
            //Thread[] t = new Thread[2];
            //for (int a = 0; a < 2; a++)
            //{
            //    t[a]=new Thread(CommentExtract);
            //    t[a].Start();
            //}
            Thread t = new Thread(CommentExtract);
            t.Name = "Extra Comment Thread";
            t.Start();

            threads = new Thread[ThreadNum];
            for (int i = 0; i < ThreadNum; i++)
            {
                threads[i] = new Thread(Process);
                threads[i].Name = "Thread " + i;
                threads[i].Start();
            }
        }

        private void CommentExtract()
        {
            var list = CommentDal.GetCommentList();
            if (list != null)
            {
                foreach (var obj in list)
                {
                    CommentQueue.Enqueue(obj);
                }
            }
        }

        public void Process()
        {
            Comment obj = null;
            while (true)
            {
                if (!CommentQueue.TryDequeue(out obj))
                {
                    Console.WriteLine("堆空了");
                    Thread.Sleep(_interval*2);
                    continue;
                }
                //Console.WriteLine(string.Format("{0}\t{1}", Thread.CurrentThread.Name, obj.Content));
                lock (writeLock)
                {
                    FileOperate.WriteFile(_logFilePath,
                        string.Format("{0}:  {1}\t{2}", DateTime.Now, Thread.CurrentThread.Name, obj.Content));
                    Thread.Sleep(_interval);
                }
            }
        }
    }
}
